<template>
  <el-row class="body">
    <el-col :span="5">
      <el-menu
        :default-active="curMenuIndex"
        class="el-menu-vertical-demo"
        mode="vertical"
        @select="handleSelect"
      >
        <el-menu-item
          v-for="(menu,index) in menuList"
          :key="index"
          style="text-align:center"
          :index="String(index)"
        >{{ menu.name }}</el-menu-item>
      </el-menu>
    </el-col>
    <el-col :span="12">
      <router-view />
    </el-col>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      menuList: [
        {
          name: '个人设置',
          path: '/shop-setting'
        },
        {
          name: '我的订单',
          path: '/shop-order'
        },
        {
          name: '购物车',
          path: '/shop-cart'
        },
        {
          name: '我的地址',
          path: '/shop-address'
        },
        {
          name: '我的收藏',
          path: '/shop-collection'
        },
        {
          name: '我的评论',
          path: '/shop-comment'
        }
      ],
      curMenuIndex: '0'
    }
  },
  watch: {
    // 监视$route对象的变化
    '$route': {
      handler(to, from) {
        this.updateMenu()
      }
    }
  },
  mounted() {
    this.updateMenu()
  },
  methods: {
    handleSelect(index) {
      this.$router.push(this.menuList[index].path)
    },
    updateMenu() {
      const currentPath = this.$route.path
      const activeItem = this.menuList.find(item => item.path === currentPath)
      let flag = 0
      for (let i = 0; i < this.menuList.length; i++) {
        if (this.menuList[i].path == currentPath) {
          this.curMenuIndex = String(i)
          flag = 1
        }
      }
      if (!flag) {
        this.curMenuIndex = String(-1)
      }
    },
    deep: true // 深度监视$route对象的变化
  }

}
</script>

<style lang="scss" scoped>

</style>
